package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.UserUnDoVo;
import com.ruoyi.system.mapper.ActivityCollectMapper;
import com.ruoyi.system.mapper.ActivityCollectUserMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 活动收集Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-04
 */
@Service
public class ActivityCollectServiceImpl implements IActivityCollectService
{
    @Autowired
    private ActivityCollectMapper activityCollectMapper;
    @Autowired
    private IActivityManagementService activityManagementService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IActivityCollectUserService activityCollectUserService;
    @Autowired
    private ActivityCollectUserMapper activityCollectUserMapper;
    @Autowired
    private IActivityLeaveService activityLeaveService;

    /**
     * 查询活动收集
     *
     * @param id 活动收集主键
     * @return 活动收集
     */
    @Override
    public ActivityCollect selectActivityCollectById(Long id)
    {
        ActivityCollect activityCollect = activityCollectMapper.selectActivityCollectById(id);
        String collectType = activityCollect.getCollectType();
        //指定活动人员
        if("1".equals(collectType)){
            String collectUser = activityCollect.getCollectUser();
            if(StringUtils.isNotBlank(collectUser)){
                List<String> userIdList = Arrays.asList(collectUser.split(","));
                ArrayList<SysUser> userList = new ArrayList();
                for(String userId : userIdList){
                    SysUser user = sysUserService.selectUserById(Long.valueOf(userId));
                    userList.add(user);
                }
                activityCollect.setCollectUserList(userList);
                activityCollect.setCollectUserIdList(userIdList);
            }
        }
        return activityCollect;
    }

    /**
     * 查询活动收集列表
     *
     * @param activityCollect 活动收集
     * @return 活动收集
     */
    @Override
    public List<ActivityCollect> selectActivityCollectList(ActivityCollect activityCollect)
    {
        List<ActivityCollect> activityCollects = activityCollectMapper.selectActivityCollectList(activityCollect);
        for(ActivityCollect vo : activityCollects){
            ActivityCollectUser activityCollectUser = new ActivityCollectUser();
            activityCollectUser.setCollectId(vo.getId());
            List<ActivityCollectUser> activityCollectUsers = activityCollectUserService.selectActivityCollectUserList(activityCollectUser);
            int size = activityCollectUsers.size();
            //收集人总数
            vo.setCollectSumCount(size);
            //已提交人数
            Integer countCounts = (int)activityCollectUsers.stream().filter(o -> o.getStatus().equals("1")||o.getStatus().equals("2")).count();
            vo.setCollectCount(countCounts);
            //未提交人数
            Integer count = (int)activityCollectUsers.stream().filter(o -> o.getStatus().equals("0")).count();
            vo.setNoCollectCount(count);
            String collectLeave = vo.getCollectLeave();
            //请假人员是否需要提交（0:不需要 1:需要）
            if("0".equals(collectLeave)){
                //查询活动请假人数
                ActivityLeave activityLeave = new ActivityLeave();
                activityLeave.setStatus("1");
                activityLeave.setActivityId(vo.getActivityId());
                int leaveSize = activityLeaveService.selectActivityLeaveList(activityLeave).size();
                //请假人员不需要提交时，收集人总数中排除请假人员
                vo.setCollectSumCount(size-leaveSize);
                //请假人员不需要提交时，未提交数据中排除请假人员
                vo.setDifferenceCount(count-leaveSize);
            }else{
                //还差多少人没有提交
                vo.setDifferenceCount(count);
            }
            //判断当前登录人是否在收集人范围内
            List<Long> userIdList = activityCollectUsers.stream().map(o -> o.getUserId()).collect(Collectors.toList());
            Long userId = activityCollect.getUserId();
            if(userIdList.contains(userId)){
                vo.setUpload(true);
            }else{
                vo.setUpload(false);
            }
        }
        return activityCollects;
    }

    /**
     * 新增活动收集
     *
     * @param activityCollect 活动收集
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertActivityCollect(ActivityCollect activityCollect)
    {
        activityCollect.setCreateTime(DateUtils.getNowDate());
        String collectUserType = activityCollect.getCollectUserType();
        //收集人
        List<String> userIdList = new ArrayList<>();
        //全体活动党员
        if("0".equals(collectUserType)){
            //查询活动参会人
            ActivityManagement activityManagement = activityManagementService.selectActivityManagementById(activityCollect.getActivityId());
            //参会人类型（0:组织党员 1:指定党员 2:全体党员）
            String activityAttendeeType = activityManagement.getActivityAttendeeType();
            if("0".equals(activityAttendeeType)){
                //本组织党员
                SysUser user = new SysUser();
                user.setDeptId(activityManagement.getDeptId());
                List<SysUser> sysUsers = sysUserService.selectUserList(user);
                userIdList = sysUsers.stream().map(o -> o.getUserId().toString()).collect(Collectors.toList());
            }else if("1".equals(activityAttendeeType)){
                //指定党员
                String activityAttendee = activityManagement.getActivityAttendee();
                if(StringUtils.isNotBlank(activityAttendee)){
                    userIdList = Arrays.asList(activityAttendee.split(","));
                }
            }else if("2".equals(activityAttendeeType)){
                //全体党员
                SysUser user = new SysUser();
                List<SysUser> sysUsers = sysUserService.selectUserList(user);
                userIdList = sysUsers.stream().map(o -> o.getUserId().toString()).collect(Collectors.toList());
            }
        }
        //指定活动内党员
        else if("1".equals(collectUserType)){
            userIdList = activityCollect.getCollectUserIdList();
            String collectUser = StringUtils.join(userIdList, ",");
            activityCollect.setCollectUser(collectUser);
        }
        int i = activityCollectMapper.insertActivityCollect(activityCollect);

        //添加人员收集信息
        for(String userId : userIdList){
            ActivityCollectUser activityCollectUser = new ActivityCollectUser();
            activityCollectUser.setUserId(Long.valueOf(userId));
            activityCollectUser.setCollectId(activityCollect.getId());
            activityCollectUserService.insertActivityCollectUser(activityCollectUser);
        }
        return i;
    }

    /**
     * 修改活动收集
     *
     * @param activityCollect 活动收集
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateActivityCollect(ActivityCollect activityCollect)
    {
        activityCollect.setUpdateTime(DateUtils.getNowDate());
        //修改收集人员
        Long id = activityCollect.getId();
        ActivityCollect activityCollectVo = selectActivityCollectById(id);
        String collectUserType = activityCollect.getCollectUserType();
        String collectUserTypeVo = activityCollectVo.getCollectUserType();
        //指定参会人员
        if("1".equals(collectUserType)&&collectUserType.equals(collectUserTypeVo)){
            List<String> collectUserIdList = activityCollect.getCollectUserIdList();
            List<String> collectUserIdListVo = activityCollectVo.getCollectUserIdList();
            //修改的人员和之前的人员不一致
            List<Long> sortedList = collectUserIdList.stream().map(Long::valueOf).sorted().collect(Collectors.toList());
            List<Long> sortedListVo = collectUserIdListVo.stream().map(Long::valueOf).sorted().collect(Collectors.toList());
            String lstStr1 = StringUtils.join(sortedList, ",");
            String lstStr2 = StringUtils.join(sortedListVo, ",");
            if(!lstStr1.equals(lstStr2)){
                activityCollectUserMapper.deleteActivityCollectUserByCollectId(id);
                for(String userId : collectUserIdList){
                    ActivityCollectUser activityCollectUser = new ActivityCollectUser();
                    activityCollectUser.setUserId(Long.valueOf(userId));
                    activityCollectUser.setCollectId(id);
                    activityCollectUser.setCreateTime(DateUtils.getNowDate());
                    activityCollectUserMapper.insertActivityCollectUser(activityCollectUser);
                }
                activityCollect.setCollectUser(lstStr1);
            }
        }
        return activityCollectMapper.updateActivityCollect(activityCollect);
    }

    /**
     * 删除活动收集信息
     *
     * @param id 活动收集主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteActivityCollectById(Long id)
    {
        int i = activityCollectMapper.deleteActivityCollectById(id);
        //删除活动收集人信息
        ActivityCollectUser activityCollectUser = new ActivityCollectUser();
        activityCollectUser.setCollectId(id);
        List<ActivityCollectUser> activityCollectUsers = activityCollectUserService.selectActivityCollectUserList(activityCollectUser);
        for(ActivityCollectUser vo : activityCollectUsers){
            activityCollectUserService.deleteActivityCollectUserById(vo.getId());
        }
        return i;
    }

    /**
     * 修改活动收集状态
     *
     * @param activityCollect 活动收集
     * @return 结果
     */
    @Override
    public int updateActivityCollectStatus(ActivityCollect activityCollect){
        return activityCollectMapper.updateActivityCollect(activityCollect);
    }

    /**
     * 查询活动收集待办任务
     *
     * @return 结果
     */
    @Override
    public List<UserUnDoVo> selectActivityCollectTask(UserUnDoVo userUnDoVo){
        return activityCollectMapper.selectActivityCollectTask(userUnDoVo);
    }
}
